<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告  条 -->
      <el-alert title="添加商品信息" type="info" center close="false" show-icon></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" align-center :active="activeIndex-0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="已完成"></el-step>
      </el-steps>
      <!-- 表单验证     -->
      <el-form
        :model="addGoodsForm"
        label-position="top"
        :rules="AddGoodsRules"
        ref="addGoodsRef"
        label-width="100px"
      >
        <!-- 标签栏 -->
        <el-tabs
          v-model="activeIndex"
          @tab-click="tabsClick"
          :before-leave="beforLeave"
          :tab-position="'left'"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 数据1 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <!-- 商品分类 -->
            <!-- 标签页切换触发 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="goodsCate"
                :props="cascaderProps"
                @change=" cascaderHandleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="cbox" v-for="cbox in item.attr_vals" :key="cbox"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 action是上传的后台地址  -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
              :headers="headers"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>商品图片
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor :v-model="addGoodsForm.goods_introduce"></quill-editor>

            <el-button type="primary" class="addBtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 下一个 -->
    </el-card>
    <!-- 提示框 -->
    <el-dialog title="提示" :visible.sync="previewImgDialogVisible" width="50%">
      <img :src="imgUrl" class="previewImg" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewImgDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="previewImgDialogVisible= false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      activeIndex: "0",
      //    添加商品表单数据
      addGoodsForm: {
        //商品名称
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [1, 3, 6],
        pics: [],
        goods_introduce: "",
        attrs:[]
      },
      AddGoodsRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ]
      },
      //   商品分类  chilren:'children'自带的
      goodsCate: [],
      cascaderProps: {
        expandTrigger: "hover",
        label: "cat_name",
        //   保存的值
        value: "cat_id"
      },
      manyTableData: [],
      onlyTableData: [],
      uploadURL: "https://www.liulongbin.top:8888/api/private/v1/upload",
      headers: {
        Authorization: window.sessionStorage.getItem("token")
      },
      previewPath: "",
      previewImgDialogVisible: false,
      imgUrl: ""
    };
  },
  created() {
    this.getGoodsCate();
  },
  methods: {
    async getGoodsCate() {
      const { data: res } = await this.$http.get(`categories`);
      //   console.log(res);

      if (res.meta.status !== 200) return this.$message.error("获取失败");
      this.$message.success("获取成功");
      //   获取成功
      this.goodsCate = res.data;
    },
    cascaderHandleChange() {
      console.log(this.addGoodsForm.goods_cat);
      if (this.addGoodsForm.goods_cat.length !== 3)
        return (this.addGoodsForm.goods_cat = []);
    },

    //当页面离开某标签页触发
    beforLeave(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error("先选择商品分类");
        return false;
      }
    },
    async tabsClick() {
      if (this.activeIndex === "1") {
        console.log(this.cateId);
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" }
          }
        );
        console.log(res);

        if (res.meta.status !== 200) return this.$message.error("獲取詩句失敗");
        this.$message.success("獲取成功");
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(",");
        });
        this.manyTableData = res.data;
      } else if (this.activeIndex === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" }
          }
        );
        console.log(res);

        if (res.meta.status !== 200) return this.$message.error("獲取詩句失敗");
        this.$message.success("獲取成功");
        this.onlyTableData = res.data;
      }
    },

    handlePreview(file) {
      this.previewImgDialogVisible = true;
      this.imgUrl = file.response.data.url;
    },
    // 删除图片
    handleRemove(file) {
      const filePath = file.response.data.tmp_path;

      const index = this.addGoodsForm.pics.findIndex(item => {
        return item.pic === file.response.data.tmp_path;
      });
      this.addGoodsForm.pics.splice(index, 1);
      console.log(this.addGoodsForm);

    },
    // 上传
    handleSuccess(res) {
      if (res.meta.status !== 200) return this.$message.error("上次失敗");
      const picInfo = { pics: res.data.tmp_path };
      this.addGoodsForm.pics.push(picInfo);
      console.log(picInfo);
    },
  addGoods() {
      var form = JSON.parse(JSON.stringify(this.addGoodsForm));

      console.log(form);
      console.log(this.addGoodsForm);
      
      form.goods_cat = form.goods_cat.join(',')
      //  console.log(form,this.addGoodsForm);
    //  为attr 设置自己的参数 
          form.attrs=[]
        // 为attrs追加 动态追加自己的属性
         this.manyTableData.forEach(item=>{
           console.log(item.attr_id,item.attr_vals);
            
            form.attrs.push({
              attr_id:item.attr_id,
              attr_vals:item.attr_vals.join(',')
            })
      })
    //  为静态追加自己的属性
         this.onlyTableData.forEach(item=>{
           console.log(item.attr_id,item.attr_vals);
            
            form.attrs.push({
              attr_id:item.attr_id,
              attr_vals:item.attr_vals
            })
      })

      this.$refs.addGoodsRef.validate(   async  flag => {
        if (!flag) return this.$message.error("重新填写完整表格");

          const{data:res}=await this.$http.post('goods',form)
          if(res.meta.status !==201) return this.$message.error(res.meta.msg)
          this.$message.success('上传成功')
          this.$router.push('/goods')
      });
    }
  },
  computed: {
    cateId() {
      return this.addGoodsForm.goods_cat.length === 3
        ? this.addGoodsForm.goods_cat[2]
        : null;
    }
  }
};
</script>
<style scoped lang="less">
.el-checkbox {
  margin: 0 5px 0 0;
}
.addBtn {
  margin: 10px 0 0 5px;
}
</style>